<template>
  <el-card :border="false" style="margin-bottom: 15px; height: 20%">
    <div class="items-center">
      <statistic-card style="width: 100%;" />
    </div>
  </el-card>

  <div class="scroll-container">
    <el-scrollbar ref="scrollbarRef">
      <el-card :border="false">
        <div v-for="mail in mails" :key="mail.id" :ref="`mail-${mail.id}`" class="card-item">
          <div class="mail-info">
            <el-tag :closable="false" class="info-tag">邮件类型：{{ mail.notification_type }}</el-tag>
            <el-tag :closable="false" class="info-tag">邮件类型说明：邀请函</el-tag>
            <el-tag :closable="false" class="info-tag">邮件发送人：{{ mail.sender_name }}</el-tag>
            <el-tag :closable="false" class="info-tag">邮件日期：{{ formatDate(mail.created_at) }}</el-tag>
          </div>
          <div>
            <el-button class="view-button" type="primary" @click="openDrawer(mail)">查看</el-button>
          </div>
        </div>
      </el-card>
    </el-scrollbar>
  </div>

  <el-drawer v-model="drawerVisible" :before-close="handleClose" :title="currentMail.notification_type" direction="rtl"
    size="40%">
    <div class="drawer-content">
      <p>邮件正文：{{ currentMail.message }}</p>
    </div>
    <template #footer>
      <el-button type="success" @click="agree(currentMail)">同意</el-button>
      <el-button type="warning" @click="closeDrawer">关闭</el-button>
    </template>
  </el-drawer>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import axios from '../http/index.js';
import { ElMessage } from "element-plus";
import StatisticCard from '../components/StatisticCard.vue';

// 模拟邮件数据
const mails = ref([]);

// 控制抽屉的显示状态
const drawerVisible = ref(false);
const currentMail = ref({});

// 日期选择器绑定的值
const selectedDate = ref(null);

// 滚动容器的引用
const scrollbarRef = ref(null);

// 获取全部的邮件
function GetAllEmails() {
  axios.get('email/getAllEmail')
    .then((response) => {
      if (response.code === 1) {
        ElMessage({
          message: '查询数据加载成功',
          type: 'success'
        });
        mails.value = response.emails;
      }
    })
    .catch((error) => {
      console.log(error);
    });
}

// 打开抽屉
const openDrawer = (mail) => {
  currentMail.value = mail;
  drawerVisible.value = true;
};

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false;
};

// 同意按钮的逻辑（可以根据需要实现具体功能）
const agree = (mail) => {
  console.log("同意按钮被点击", mail);
  axios.post('team/agree', mail)
    .then((response) => {
      if (response.code === 1) {
        ElMessage({
          message: response.message,
          type: 'success'
        })
      }
    })
    .catch((error) => {
      console.log(error);
    })
  closeDrawer();
};

// 抽屉关闭前的回调
const handleClose = (done) => {
  closeDrawer();
  done();
};

// 日期选择器值变化时的处理
const onDateChange = () => {
  if (!selectedDate.value) return;

  // 将选择的日期格式化为年月
  const selectedYear = new Date(selectedDate.value).getFullYear();
  const selectedMonth = new Date(selectedDate.value).getMonth();

  // 找到最接近选择日期的邮件
  let closestMail = null;
  let minDiff = Infinity;

  mails.value.forEach(mail => {
    const mailDate = new Date(mail.created_at);
    const diff = Math.abs(
      (mailDate.getFullYear() - selectedYear) * 12 + mailDate.getMonth() - selectedMonth
    );
    if (diff < minDiff) {
      minDiff = diff;
      closestMail = mail;
    }
  });

  if (closestMail) {
    // 滚动到最接近的邮件
    const targetElement = document.querySelector(`[ref="mail-${closestMail.id}"]`);
    if (targetElement) {
      targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  } else {
    ElMessage({
      message: '未找到匹配的邮件',
      type: 'warning'
    });
  }
};

// 格式化日期为 YYYY-MM-DD
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toISOString().split('T')[0];
};

onMounted(() => {
  GetAllEmails();
});
</script>

<style scoped>
.scroll-container {
  height: 70%;
}

.card-item {
  margin: 10px;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  background-color: #d4d4d4;
  padding: 0 20px;
  box-sizing: border-box;
}

.mail-info {
  display: flex;
  align-items: center;
  flex-grow: 1;
  overflow: hidden;
}

.info-tag {
  margin-right: 10px;
  white-space: nowrap;
}

.view-button {
  margin-left: 10px;
}

.drawer-content {
  padding: 10px;
}
.items-center {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>